package ele_handler

import (
	"go-yuque/yuque/extend"
	"strings"
)

func init() {
	registerInitFunc(
		func() YuqueElementHandler {
			h := &tableHandlerStruct{}
			h.elements = []string{"table"}
			return h
		},
		func() YuqueElementHandler {
			h := &trTdHandlerStruct{}
			h.elements = []string{"tr", "td"}
			return h
		})
}

// 表格 table 处理类
type tableHandlerStruct struct {
	BaseHandler
}

func (t *tableHandlerStruct) preHandle() (err error) {
	// 注入 table 标记
	t.ctxMap["wrapTable"] = true
	return
}

func (t *tableHandlerStruct) postHandle() (err error) {
	// 恢复 table 标记
	delete(t.ctxMap, "wrapTable")
	// 删除行下标变量
	delete(t.ctxMap, _TR_IDX)
	return
}

// ------------------ tr td 处理类 ------------------

// 行下标 Key
const _TR_IDX = "_TR_IDX"

// 列下标 Key
const _TD_IDX = "_TD_IDX"

type trTdHandlerStruct struct {
	BaseHandler
	trIdx int // 行下标
	tdIdx int // 列下标
	extend.BufferStruct
}

func (t *trTdHandlerStruct) preHandle() (err error) {
	// 切换缓冲区
	t.ChangeToBuffer(t.textContentP)

	if t.node.Data == "tr" {
		t.WriteInBuffer("| ")

		// 标记行下标
		trIdxs, trIdxsOk := t.ctxMap[_TR_IDX].([]int)
		if trIdxsOk {
			t.trIdx = trIdxs[len(trIdxs)-1] + 1
			trIdxs = append(trIdxs, t.trIdx)
			t.ctxMap[_TR_IDX] = trIdxs
		} else {
			t.trIdx = 1
			t.ctxMap[_TR_IDX] = []int{t.trIdx}
		}
	} else if t.node.Data == "td" {
		// 标记列下标
		tdIdxs, tdIdxsOk := t.ctxMap[_TD_IDX].([]int)
		if tdIdxsOk {
			t.tdIdx = tdIdxs[len(tdIdxs)-1] + 1
			tdIdxs = append(tdIdxs, t.tdIdx)
			t.ctxMap[_TD_IDX] = tdIdxs
		} else {
			t.tdIdx = 1
			t.ctxMap[_TD_IDX] = []int{t.tdIdx}
		}
	}

	return
}

func (t *trTdHandlerStruct) postHandle() (err error) {
	if t.node.Data == "tr" {
		// 需要将 td 里被替换的缓冲区内容写回来
		t.WriteInBuffer(t.GetTextContext())

		// 如果是第一行，就要加一行列长度的 | ---------- |
		if t.trIdx == 1 {
			sbT := strings.Builder{}
			// 获取列长度
			tdIdxs, tdIdxsOk := t.ctxMap[_TD_IDX].([]int)
			if tdIdxsOk {
				sbT.WriteString("\n|")
				for i := 0; i < len(tdIdxs); i++ {
					sbT.WriteString("---------- |")
				}
				sbT.WriteString("\n")
			}
			t.WriteInBuffer(sbT.String())
		} else {
			t.WriteInBuffer("\n")
		}
		// 删除列长度变量
		delete(t.ctxMap, _TD_IDX)
	} else if t.node.Data == "td" {
		// td 是单元格
		context := t.GetTextContext()
		if len(context) >= 5 {
			lastStr := context[len(context)-5:]
			if lastStr == "<br/>" {
				t.WriteInBuffer(context[:len(context)-5])
			} else {
				t.WriteInBuffer(context)
			}
		} else {
			t.WriteInBuffer(context)
		}

		t.WriteInBuffer(" | ")
	}

	// 恢复缓冲区
	t.RecoverFromBuffer(t.textContentP)
	return
}
